<template>
  <div class="order-management-page">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <h1 style="margin: 0">订单管理</h1>
      </div>

      <!-- 没有订单 -->
      <el-empty v-if="orders.length === 0" description="暂无订单"></el-empty>

      <!-- 订单列表 -->
      <div v-else>
        <el-table :data="orders" style="width: 100%" stripe border>
          <el-table-column prop="orderId" label="订单号" width="180"></el-table-column>
          <el-table-column prop="customerId" label="用户ID"></el-table-column>
          <el-table-column prop="orderStatus" label="发货状态">
            <template #default="scope">
              <el-tag :type="scope.row.orderStatus ? 'success' : 'warning'">
                {{ scope.row.orderStatus ? "已发货" : "未发货" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" label="总金额">
            <template #default="scope">
              ￥{{ scope.row.totalPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button
                  v-if="!scope.row.orderStatus"
                  type="primary"
                  size="small"
                  @click="sendShipmentEmail(scope.row)"
              >
                发货
              </el-button>
              <el-button
                  v-if="!scope.row.orderStatus"
                  type="danger"
                  size="small"
                  @click="cancelOrder(scope.row)"
              >
                取消
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.order-management-page {
  padding: 20px;
}

.box-card {
  max-width: 1200px;
  margin: 0 auto;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>
<script lang="ts">
import axios from 'axios';
import { defineComponent, ref, onMounted } from 'vue';
import type {Order} from "../../types.ts";
import router from "../../router";

export default defineComponent({
  name: 'OrderManagement',
  setup() {
    const orders = ref<Order[]>([]);

    const loadOrders = async () => {
      try {
        const response = await axios.get('/api/order');
        orders.value = response.data;
      } catch (error) {
        console.error('加载订单失败:', error);
        if (error.response) {
          alert('服务器返回错误:'+error.response.data);
        }
      } finally {

      }
    };



    // 取消订单
    const cancelOrder = async (order: any) => {
      try {
        const response = await axios.delete(`/api/order/${order.orderId}`);
        if (response.status === 200) {
          alert('订单已取消');
          await loadOrders(); // 重新加载订单列表
        }
      } catch (error) {
        console.error('取消订单失败:', error);
        alert('取消订单失败，请稍后重试。');
      }
    };

// 发送发货确认邮件
    const sendShipmentEmail = async (order: any) => {
      try{
        await axios.put(`/api/order/${order.orderId}/status`, null, {
          params: {
            status: true, // 发送邮件时，将订单状态更新为 true（已发货）
          }
        });
        alert("订单已发货");
      }catch (error){
        alert("发货失败:"+error);
      }
      try {

        const response = await axios.post(`/api/order/${order.orderId}/send-email`);
        if (response.status === 200) {
          console.log('发货确认邮件已发送');
        }
      } catch (error) {
        console.error('发送发货确认邮件失败:', error);
        //alert('发送邮件失败，请稍后重试。');
      }
    };
    const Logout = () => {
      sessionStorage.setItem('isLoggedIn','false');
      sessionStorage.setItem('username','');
      sessionStorage.setItem('userId','');
      router.push({ path: "/login" });
      return;
    };

    // 初始化加载订单
    onMounted(() => {
      loadOrders();
    });

    return {
      orders,
      loadOrders,
      sendShipmentEmail,
      cancelOrder,
      Logout,
    };
  },
});
</script>

<style scoped>
.order-management-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px;
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
  border-radius: 15px;
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
  margin-bottom: 40px;
  font-size: 2.5rem;
  color: #333;
  font-weight: 700;
}

.loading-indicator {
  text-align: center;
  font-size: 1.5rem;
  color: #007bff;
}

.no-orders {
  text-align: center;
  font-size: 1.2rem;
  color: #555;
}

.order-list {
  max-width: 1200px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.order-item {
  display: table-column;
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.order-info {
  margin-bottom: 20px;
}

.order-actions {
  display: flex;
  justify-content: space-between;
}

.ship-btn,
.cancel-btn {
  padding: 8px 16px;
  font-size: 1.1rem;
  border-radius: 5px;
  cursor: pointer;
}

.ship-btn {
  background-color: #28a745;
  color: white;
  border: none;
}

.ship-btn:hover {
  background-color: #218838;
}

.cancel-btn {
  background-color: #dc3545;
  color: white;
  border: none;
}

.cancel-btn:hover {
  background-color: #c82333;
}
</style>
